<?php

namespace Flyweight;


/**
 * 享元模式类似与容器
 * Class Client
 * @package Flyweight
 */
class Client
{
    public static function main()
    {
        $flyweightFactory = new FlyweightFactory();
        $flyweight1 = $flyweightFactory->getFlyweight('A');
        $flyweight1->operation(new UnsharedFlyweight('runtime info1'));

        $flyweight2 = $flyweightFactory->getFlyweight('A');
        $flyweight2->operation(new UnsharedFlyweight('runtime info2'));
    }
}


interface Flyweight
{
    public function operation(UnsharedFlyweight $unsharedFlyweight): void;
}
class FlyweightA implements Flyweight
{
    protected string $key;

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    public function operation(UnsharedFlyweight $unsharedFlyweight): void
    {
        echo "具体享元: " , $this->key, " 被调用", PHP_EOL;
        echo "非享元信息是: " , $unsharedFlyweight->getInfo(), PHP_EOL;
    }
}

class FlyweightFactory
{
    protected array $flyweightMap;

    public function getFlyweight(string $key): Flyweight
    {
        if (!isset($this->flyweightMap[$key])) {
            $this->flyweightMap[$key] = new FlyweightA($key);
        }
        return $this->flyweightMap[$key];
    }
}


class UnsharedFlyweight
{
    private string $info;

    public function __construct(string $info)
    {
        $this->info = $info;
    }

    public function getInfo(): string
    {
        return $this->info;
    }

    public function setInfo(string $info): void
    {
        $this->info = $info;
    }
}


Client::main();
